package com.study.lihan.threalLocal;

import com.study.lihan.bean.Student;

import javax.sound.midi.Soundbank;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author: lihan
 * @Date : 2022/1/2- 01
 * @DESCRIPTION: com.study.lihan.threalLocal
 * @version: 1.0
 */
public class TestPhantomReference {
    private static  final List<Object> list = new LinkedList<>();
    private static  final ReferenceQueue<Student> QUEUE = new ReferenceQueue<>();
    public static void main(String[] args) {
        PhantomReference<Student> phantomReference = new PhantomReference<>(new Student(), QUEUE);
//用来撑爆内存
        new Thread(()->{
            while (true){
                list.add(new byte[1024*1024]);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();
                }
                System.out.println(phantomReference.get());
            }
        }).start();
//对象被回收需要放到这个队列中
        new Thread(()->{
            while (true){
                Reference<? extends  Student> poll = QUEUE.poll();
                if(poll != null){
                    System.out.println("虚引用对象被回收了----"+poll);
                }

            }
        }).start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
